package com.gonfre.quientelo;

import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gc.materialdesign.widgets.Dialog;

import java.util.ArrayList;

import util.AsyncRequest;
import util.AutocompleteCustomArrayAdapter;
import util.CustomAutoCompleteTextChangedListener;
import util.CustomAutoCompleteView;
import util.DataBaseManager;
import util.MyDBObject;
import util.MyDataBase;
import util.MyParameters;
import util.Response;


public class RequestPriceActivity extends MyMenuActivity {

    public String selectedCategories = "";
    public String selectedCategoriesName = "";

    // for database operations
    /*public MyDataBase dbLocations;
    public CustomAutoCompleteView myAutoComplete;
    public ArrayAdapter<MyDBObject> myAdapter;*/

    public Integer cntLocations = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request_price);
        //myAutoCompletes = new CustomAutoCompleteView[10];
        myAutoCompletes = new ArrayList <CustomAutoCompleteView> ();
        myAdapters = new ArrayList <ArrayAdapter<MyDBObject>> ();
        EditText t4 = (EditText)findViewById(R.id.editTextCategory);
        t4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Trace RegisterSellerActivity 'setOnItemClickListener'", "editTextCategories");
                Intent intent=new Intent(getApplicationContext(), MultiSelectorActivity.class);
                intent.putExtra("multiSelector", false);
                intent.putExtra("selectedItems", selectedCategories);
                intent.putExtra("selectedItemsName", selectedCategoriesName);
                startActivityForResult(intent, 1);
            }
        });

        initLocations();

        initGalery();
    }


    @Override
    public void onFinishRequest(int type, Response res) {
        stopProgressBarCircular(R.id.progressBarRequestPriceLayout);
        Dialog dialog = new Dialog(this,null, res.getHeaderResponse().toString() + "-" + res.getHeaderMessage());
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bundle res = data.getExtras();
                    selectedCategories = res.getString("selectedItems");
                    selectedCategoriesName = res.getString("selectedItemsName");
                    Log.i("Trace RegisterSellerActivity 'onActivityResult' selectedCategories", selectedCategories);
                    Log.i("Trace RegisterSellerActivity 'onActivityResult' selectedCategoriesName", selectedCategoriesName);
                    TextView t0 = (TextView)findViewById(R.id.editTextCategory);
                    t0.setText(selectedCategoriesName);
                }
                break;
            case 21:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = data.getData();
                    //Log.i("Trace RegisterSellerActivity 'onActivityResult' getPath(selectedImage)", getPath(selectedImage));
                    ImageView photoRequestPrice1 = (ImageView)findViewById(R.id.photoRequestPrice1);
                    photoRequestPrice1.setImageURI(selectedImage);
                }
                break;

            case 22:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = data.getData();
                    //Log.i("Trace RegisterSellerActivity 'onActivityResult' getPath(selectedImage)", getPath(selectedImage));
                    ImageView photoRequestPrice1 = (ImageView)findViewById(R.id.photoRequestPrice2);
                    photoRequestPrice1.setImageURI(selectedImage);
                }
                break;

            case 23:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = data.getData();
                    //Log.i("Trace RegisterSellerActivity 'onActivityResult' getPath(selectedImage)", getPath(selectedImage));
                    ImageView photoRequestPrice1 = (ImageView)findViewById(R.id.photoRequestPrice3);
                    photoRequestPrice1.setImageURI(selectedImage);
                }
                break;
        }
    }

    private void initGalery(){
        ImageView img1 = (ImageView)findViewById(R.id.photoRequestPrice1);
        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, 21);
            }
        });

        TextView txt1 = (TextView)findViewById(R.id.textIcon1);
        txt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView photoRequestPrice1 = (ImageView)findViewById(R.id.photoRequestPrice1);
                Resources res = getResources();
                Drawable drawable = res.getDrawable( R.drawable.no_foto );
                photoRequestPrice1.setImageDrawable(drawable);
            }
        });

        ImageView img2 = (ImageView)findViewById(R.id.photoRequestPrice2);
        img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, 22);
            }
        });

        TextView txt2 = (TextView)findViewById(R.id.textIcon2);
        txt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView photoRequestPrice1 = (ImageView)findViewById(R.id.photoRequestPrice2);
                Resources res = getResources();
                Drawable drawable = res.getDrawable( R.drawable.no_foto );
                photoRequestPrice1.setImageDrawable(drawable);
            }
        });

        ImageView img3 = (ImageView)findViewById(R.id.photoRequestPrice3);
        img3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, 23);
            }
        });

        TextView txt3 = (TextView)findViewById(R.id.textIcon3);
        txt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView photoRequestPrice1 = (ImageView)findViewById(R.id.photoRequestPrice3);
                Resources res = getResources();
                Drawable drawable = res.getDrawable( R.drawable.no_foto );
                photoRequestPrice1.setImageDrawable(drawable);
            }
        });
    }

    private String getPath(Uri uri) {
        String[] projection = { android.provider.MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(android.provider.MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void initLocations(){
        ImageView img = (ImageView)findViewById(R.id.buttonAddLocation);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Trace RequestPriceActivity 'setOnItemClickListener'", "buttonAddLocation");
                addLocation(++cntLocations);
            }
        });
        addLocation(++cntLocations);
    }

    private void addLocation(int idTextLocation){
        final Integer idTextLocationF = 100+idTextLocation;
        // Se obtiene el LinearLayout de Locations
        LinearLayout layoutRoot = (LinearLayout)findViewById(R.id.layoutLocations);

        // Se crea el nuevo relative Layout hijo
        RelativeLayout layoutChild = new RelativeLayout(this);
        layoutChild.setId(idTextLocationF);
        RelativeLayout.LayoutParams layoutParamsChild = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutChild.setLayoutParams(layoutParamsChild);

        // Agrega CustomAutoCompleteView
        util.CustomAutoCompleteView editTextLocation = new util.CustomAutoCompleteView(this);
        editTextLocation.setId(idTextLocation);
        editTextLocation.setEms(10);
        setLayoutParams(editTextLocation, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.ALIGN_PARENT_LEFT, 0, 20, 50, 0);
        initEditTextLocation(editTextLocation, idTextLocation);
        layoutChild.addView(editTextLocation);

        // Si es la segunda location en adelante se agrega el boton de eliminar location
        if(cntLocations > 1) {
            final int j = idTextLocation-1;
            // Agrega Imagen Button Delete
            ImageButton imgDelete = new ImageButton(this);
            //imgDelete.setImageResource(R.drawable.ic_remove_circle_outline_grey600_24dp);
            imgDelete.setImageResource(R.drawable.ic_highlight_remove_grey600_24dp);
            imgDelete.setBackgroundResource(R.drawable.none);
            imgDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Log.i("Trace RequestPriceActivity 'setOnItemClickListener'", "imgDelete");
                    myAutoCompletes.get(j).setItemId("null");
                    LinearLayout layoutRoot = (LinearLayout) findViewById(R.id.layoutLocations);
                    RelativeLayout layoutChild = (RelativeLayout) findViewById(idTextLocationF);
                    layoutRoot.removeView(layoutChild);
                }
            });
            setLayoutParams(imgDelete, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.CENTER_VERTICAL, 0, 0, 0, 0);
            layoutChild.addView(imgDelete);
        }

        // Agrega Layout hijo a Layout Padre
        layoutRoot.addView(layoutChild);
    }

    private void setLayoutParams(View v, int w, int centerInParent, int marginLeft, int marginTop, int marginRight, int marginBottom) {
        // Defining the layout parameters of the Button
        RelativeLayout.LayoutParams layoutParameters = new RelativeLayout.LayoutParams(w, RelativeLayout.LayoutParams.WRAP_CONTENT);

        // Add Margin to the LayoutParameters
        layoutParameters.setMargins(marginLeft, marginTop, marginRight, marginBottom);

        // Add Rule to Layout
        layoutParameters.addRule(centerInParent);

        // Setting the parameters on the Button
        v.setLayoutParams(layoutParameters);
    }

    private void setLayoutParams(View v, int w, int centerInParent1, int centerInParent2, int marginLeft, int marginTop, int marginRight, int marginBottom) {
        // Defining the layout parameters of the Button
        RelativeLayout.LayoutParams layoutParameters = new RelativeLayout.LayoutParams(w, RelativeLayout.LayoutParams.WRAP_CONTENT);

        // Add Margin to the LayoutParameters
        layoutParameters.setMargins(marginLeft, marginTop, marginRight, marginBottom);

        // Add Rule to Layout
        layoutParameters.addRule(centerInParent1);
        layoutParameters.addRule(centerInParent2);

        // Setting the parameters on the Button
        v.setLayoutParams(layoutParameters);
    }

    private void setLayoutParams(View v, int centerInParent) {
        // Just call the other AddButtonLayout Method with Margin 0
        setLayoutParams(v, RelativeLayout.LayoutParams.WRAP_CONTENT, centerInParent, 0, 0, 0, 0);
    }

    private void initEditTextLocation(CustomAutoCompleteView textLocation, int idTextLocation){
        DataBaseManager dbm = new DataBaseManager(this);
        String table = this.getString(R.string.table_ubicacion);
        String sql_table = this.getString(R.string.sql_ubicacion);
        dbLocations = new util.MyDataBase(this, dbm, table, sql_table);
        final int j = idTextLocation-1;

        //myAutoCompletes[j] = textLocation;//(CustomAutoCompleteView) findViewById(idTextLocation);
        myAutoCompletes.add(textLocation);

        //myAutoCompletes[j].setOnItemClickListener(new AdapterView.OnItemClickListener() {
        myAutoCompletes.get(j).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {

                RelativeLayout rl = (RelativeLayout) arg1;
                TextView tv = (TextView) rl.getChildAt(0);
                myAutoCompletes.get(j).setText(getShortLocationName(tv.getText().toString()));
                myAutoCompletes.get(j).setItemId("" + tv.getId());
                Log.i("Trace RegisterPriceActivity 'setOnItemClickListener' tv.getId()", "" + tv.getId());
            }

        });

        // add the listener so it will tries to suggest while the user types
        myAutoCompletes.get(j).addTextChangedListener(new CustomAutoCompleteTextChangedListener(this, j));

        // ObjectItemData has no value at first
        MyDBObject[] ObjectItemData = new MyDBObject[0];

        // set the custom ArrayAdapter
        myAdapters.add(new AutocompleteCustomArrayAdapter(this, R.layout.list_view_row, ObjectItemData, null));
        myAutoCompletes.get(j).setAdapter(myAdapters.get(j));
    }

    public String getLocationsRequestPrice(){
        String res = "";
        String tmp = "";
        CustomAutoCompleteView t0;
        for(int i=1;i<=cntLocations;i++){
            //t0 = (CustomAutoCompleteView)findViewById(cntLocations);
            try {
                tmp = ""+myAutoCompletes.get(i-1).getItemId();
            }catch (Exception e){
                tmp="null";
            }
            if(tmp.compareTo("null") != 0)
                res = res+","+tmp;
        }

        if(res.compareTo("")!=0)
            res = res.substring(1);
        Log.i("Trace RegisterPriceActivity 'getLocationsRequestPrice' res:", res);
        return res;
    }

    public void buttonSendOnClick(View w) {
        AsyncRequest req = new AsyncRequest(this);
        Response res = new Response();
        Dialog dialog;

        String pDescription = getViewValueStr(R.id.editTextDescription);
        String pCategory = selectedCategories;
        String pLocations = getLocationsRequestPrice();
        String pOnlyPhoto;
        android.support.v7.widget.SwitchCompat c0 = (android.support.v7.widget.SwitchCompat) findViewById(R.id.switchPhoto);
        if (c0.isChecked()){
            pOnlyPhoto = "S";
        }else{
            pOnlyPhoto = "N";
        }

        boolean passValidations = true;

        MyParameters p = new util.MyParameters();

        p.add(pDescription, "Descripcion");
        p.add(pCategory, "Categoria");
        p.add(pLocations, "Ubicación");

        String mandatory = p.validateMandatoryData();
        if(mandatory.compareTo("") != 0){
            passValidations = false;
            dialog = new Dialog(this,null, mandatory);
            dialog.show();
            return;
        }

        if(passValidations){
            startProgressBarCircular(R.id.progressBarRequestPriceLayout);
            res = req.xRequestPrice(pDescription, Integer.parseInt(pCategory), pLocations, pOnlyPhoto);
        }

    }

}
